package etnorservice.etnor_service.aop.aspect;
import etnorservice.etnor_service.aop.annoution.Permission;
import etnorservice.etnor_service.service.UserService;
import etnorservice.etnor_service.utils.JwtTokenUtil;
import etnorservice.etnor_service.exception.UnauthorizedException;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
public class PermissionAspect {

    @Autowired
    private UserService userService;

    // 定义环绕通知
    @Around("@annotation(permission)")
    public Object checkPermission(ProceedingJoinPoint joinPoint, Permission permission) throws Throwable {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String authorizationHeader = extractAuthorizationHeader(request);
        if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
            throw new UnauthorizedException(40001, "未授权");
        }

        String token = authorizationHeader.substring(7); // 去掉"Bearer "前缀
        String account = new JwtTokenUtil().getAccountFromToken(extractTokenFromHeader(authorizationHeader));

        int role = userService.findRoleByAccount(Integer.parseInt(account)).getRole();

        // 检查角色是否符合要求
        if (role > permission.value()) {
            throw new UnauthorizedException(40001, "无权限访问");
        }

        return joinPoint.proceed(); // 继续执行目标方法
    }

    private String extractAuthorizationHeader(HttpServletRequest request) {
        // 从实际请求中获取Authorization头部
        return request.getHeader("Authorization");
    }

    private String extractTokenFromHeader(String header) {
        if (header == null || !header.startsWith("Bearer ")) {
            return null;
        }
        return header.substring(7).trim(); // 去除 "Bearer ".length() 后面的空格
    }
}
